package com.example.codingchallenge;

import java.sql.Timestamp;
import java.util.ArrayList;

import com.att.intern.webservice.Incident;
import com.att.intern.webservice.Webservice;
import com.att.intern.webservice.Webservice.TokenInvalidException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class SearchLocations extends Activity {

	private EditText geolocET;
	private Button searchButton;
	private int zipCode;
	private ArrayList<Incident> searchResults = null;
	private int position;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_locations);
		
		geolocET = (EditText) findViewById(R.id.geolocTextField);
		searchButton = (Button) findViewById(R.id.searchButton);
		
		// -1 is a Sentinel Value for no results found.
		zipCode = -1;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.search_locations, menu);
		return true;
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		
		if (MainActivity.logoff)
			finish();
	}
	
	
	public void searchGeoloc(View view)
	{
		// Hide keyboard input.
		InputMethodManager inputMethodManager = (InputMethodManager)  SearchLocations.this.getSystemService(Activity.INPUT_METHOD_SERVICE);
	    inputMethodManager.hideSoftInputFromWindow(SearchLocations.this.getCurrentFocus().getWindowToken(), 0);
	
	    // Use REGEX to see if it is a 5 digit code.
	    String geoloc = geolocET.getText().toString();
	    try
	    {
	    	
	    	zipCode = Integer.parseInt(geoloc);
	    	
	    	if (geoloc.length() != 5)
	    	{	
	    		AlertDialog.Builder builder = new AlertDialog.Builder(this);
				
				builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
					{
	                public void onClick(DialogInterface dialog, int id) {
	                    // User cancelled the dialog
	                }
	            });

				// 2. Chain together various setter methods to set the dialog characteristics
				builder.setMessage("Invalid geoloc code.")
				       .setTitle("ERROR");

				// 3. Get the AlertDialog from create()
				AlertDialog dialog = builder.create();
				
				
				// 4. Show the dialog box.
				dialog.show();
				
				return;
	    	}
	    }
	    catch (Exception e)
	    {
	    	geolocET.setHint("Please insert a geoloc.");
	    	return;
	    }
	   
	
		
		Intent intent = getIntent();
		String token = intent.getStringExtra("token"); System.out.println("token-2: " + token);
		
		// Start thread using Asynctask
		new SearchThread(this, token, zipCode).execute();
	}
	
	
	
	
	public void storePosition(int position)
	{
		this.position = position;
		System.out.println("Position: " + position);
		Intent intent = new Intent(SearchLocations.this, IncidentInformation.class);
		intent.putExtra("Incident", searchResults.get(position));
		startActivity(intent);
	}
	
	public void logOff(View view)
	{
		finish();
	}
	
	
	
	
	final class SearchThread extends AsyncTask<Void, Integer, ArrayList<Incident>>
	{
		private final Activity parent;
		private final String token;
		private final int zipCode;
		public SearchThread(final Activity parent, String token, int zipCode)
		{
			this.parent = parent;
			this.token = token;
			this.zipCode = zipCode;
		}
		
		@Override
		protected void onPreExecute()
		{
			geolocET.setText("Finding " + geolocET.getText().toString() + "...");
			
			geolocET.setFocusable(false);
			searchButton.setEnabled(false);
		}

		@Override
		protected ArrayList<Incident> doInBackground(Void... arg0) 
		{	
			Webservice web = new Webservice(parent);

			try 
			{
				searchResults = web.geolocSearch(token, zipCode);
			} 
			catch (TokenInvalidException e) 
			{
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
			
			return searchResults;
		}
		
		
		@Override
		protected void onPostExecute(ArrayList<Incident> searchResults) {
			super.onPostExecute(searchResults);
			
			geolocET.setFocusableInTouchMode(true);
			searchButton.setEnabled(true);
			
			guiControl(searchResults);
		}
		 

		protected void guiControl(ArrayList<Incident> searchResults)
		{
			// DEBUG Print building names
			for (int i = 0; i < searchResults.size(); i++)
			{
				System.out.println(searchResults.get(i).getBuildingName());
			}
			
		
			// **********************************
			displayBuildingNames(searchResults);
		}
		
	}
	
	public void displayBuildingNames(ArrayList<Incident> searchResults)
	{
		geolocET.setText(zipCode + "");
		
		int size = searchResults.size();
		
		if (size != 0)
		{
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
			
			for (int i = 0; i < size; i++)
			{
				adapter.add(searchResults.get(i).getBuildingName());
			}
			
			
			ListView lv = (ListView) findViewById(R.id.listView1);
			// Display the ListView items on the activity.
			lv.setAdapter(adapter);
			
			lv.setOnItemClickListener(new ListView.OnItemClickListener()
			{
	
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int index,
						long arg3) {
						
						storePosition(index);
					}
			});
		}
		else if (size == 0)
		{
			/*ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
			adapter.add("No results found :(");
			ListView lv = (ListView) findViewById(R.id.listView1);
			// Display the ListView items on the activity.
			lv.setAdapter(adapter);
			
			lv.setOnItemClickListener(new ListView.OnItemClickListener()
			{
	
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int index,
						long arg3) {
						
						addIncidentActivity();
					}
			});*/
			
			// 1. Instantiate an AlertDialog.Builder with its constructor
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			
			builder.setPositiveButton("Create Incident", new DialogInterface.OnClickListener() 
				{
                public void onClick(DialogInterface dialog, int id) {
                    // Create the incident
                	addIncidentActivity();
                }
            })			
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
				{
                public void onClick(DialogInterface dialog, int id) {
                    // User cancelled the dialog
                }
            });



			// 2. Chain together various setter methods to set the dialog characteristics
			builder.setMessage("No prior incidents found")//R.string.dialog_message)
			       .setTitle("No Incidents");//R.string.dialog_title);

			// 3. Get the AlertDialog from create()
			AlertDialog dialog = builder.create();
			
			
			// 4. Show the dialog box.
			dialog.show();
		}
	}
	
	public void addIncidentActivity()
	{
		Intent intent = new Intent(this, AddIncident.class);
		startActivity(intent);
	}
}
